/**
 * created by kosmo on 07/06/2017.
 */



Dropzone.autoDiscover = false;

window.addEventListener("load", function () {
    DropZoneStorageMain.init();
});



const DropZoneStorageMain = {

    init: function () {
        DropZoneStorage.init();
        StorageDetailBox.init();
    }

};



const DropZoneStorage = {

    _boxDiv_:null,


    _detailMessageKey_: "data-detail-key",
    _fileIndex_: 0,
    _msgMap_: {},

    _urlMap_:{},

    _lockBtn_:null,

    _dropzone_:null,

    _form_:null,

    _dropZoneOptions_:{
        autoDiscover: false,
        maxFilesize: 20971520,
        uploadMultiple: false,
        addRemoveLinks: true,
        dictDefaultMessage: "拖拽或点击以上传",
        dictFallbackMessage: "您的浏览器不支持拖拽上传",
        dictInvalidFileType: "您上传的文件格式错误",
        dictFallbackText: "请使用传统的表单上传 ,像往常一样",
        dictCancelUpload: "取消上传",
        dictMaxFilesExceeded: "你不能上传更多的文件",
        dictCancelUploadConfirmation: "确定要取消上传吗?",
        dictRemoveFile: "清除",
        //headers:headerObj,
        accept: function (file, done) {

           /* if(!DropZoneStorage.allowUpload()){
                done("没有指定目录");
                return;
            }*/

            if (!DropZoneStorage.isExpectFile(file)) {
                // 显示错误
                done("不是 video");
            } else if (file.size > 1262485504) {
                // 大小大于 1 G,显示错误 1262485504
                done("大小不超过 1 G");
            } else {
                // 正确,上传
                done();
            }

        },
        init: function () {
            this.on("success", function (file, result) {
                if (result.status === true) {
                    if (file.previewElement) {
                        DropZoneStorage.success(file, result);
                    }
                } else {
                    if (file.previewElement) {
                        DropZoneStorage.failure(file, result);
                    }
                }
            });
            this.on("error",function (file,errorMsg,xhr) {
                DropZoneStorage.error(file,errorMsg,xhr);
            });
            this.on("addedfile", function (file) {
                DropZoneStorage.addFile(file);
            });
            this.on("removedfile", function (file) {
                DropZoneStorage.removeFile(file);
            });
            this.on("complete", function (file) {
                DropZoneStorage.complete(file);
            })
        }
    },
    init: function () {
        this._boxDiv_ = document.querySelector("div.box.upload");
        this._form_ = this._boxDiv_.querySelector("form.upload.dropzone");



        //初始化表单事件
        DropZoneStorageEvent.init(this._boxDiv_,this._form_);

        this._dropzone_ = new Dropzone("form.upload.dropzone", this._dropZoneOptions_);

    }, getFileIndex: function () {
        return ++this._fileIndex_;
    }, upload: function () {

    }, isExpectFile: function (file) {
        return true;
    }, addFile: function (file) {
        file.previewElement.setAttribute(this._detailMessageKey_, this.getFileIndex());

    }, removeFile: function (file) {

    }, complete: function (file) {

    }, success: function (file, result) {

        file.previewElement.title = "点击查看详情";

        try {
            this.__putUrl__(file.name, result.data.url);
        } catch (e){
            console.error("result[%s] is error",result);
        }

        file.previewElement.addEventListener("click", function () {
            let msg;
            msg =  DataUtils.convertAsMapString(result.data);

            StorageDetailBox.show(file.name, msg);

        });

        file.previewElement.classList.add("dz-success");

    }, failure: function (file, result) {
        let node, _i, _len, msgDivs, _this;
        file.previewElement.classList.add("dz-error");
        file.previewElement.title = "点击查看详情";
        msgDivs = file.previewElement.querySelectorAll("[data-dz-errormessage]");
        for (_i = 0, _len = msgDivs.length; _i < _len; _i++) {
            node = msgDivs[_i];
            node.innerHTML = result.msg;
        }
        file.previewElement.setAttribute(this._detailMessageKey_, result.msg);
        _this = this;

        file.previewElement.addEventListener("click", function () {
            let msg;
            msg = this.getAttribute(_this._detailMessageKey_);

            StorageDetailBox.show(file.name,msg);
        });
    },error:function (file,errorMsg,xhr) {
        let node, _i, _len, msgDivs, _this,msg;
        file.previewElement.classList.add("dz-error");
        file.previewElement.title = "点击查看详情";
        msgDivs = file.previewElement.querySelectorAll("[data-dz-errormessage]");
        for (_i = 0, _len = msgDivs.length; _i < _len; _i++) {
            node = msgDivs[_i];
            node.innerHTML = xhr.status + " : " + errorMsg.error;
        }

        msg = DataUtils.convertAsMapString(errorMsg);
        file.previewElement.setAttribute(this._detailMessageKey_,msg);

        _this = this;
        file.previewElement.addEventListener("click", function () {
            let msg;
            msg = this.getAttribute(_this._detailMessageKey_);

            StorageDetailBox.show(file.name,msg);
        });
    },__putUrl__:function (fileName,url) {
        this._urlMap_[fileName] = url;
    },forEachUrl:function () {
        return DataUtils.convertAsMapString(this._urlMap_);
    },allowUpload:function () {
        return this._form_.directory.value != null && this._form_.directory.value !== "";
    }


};

const DropZoneStorageEvent = {

    _boxDiv_:null,

    _lockBtn_:null,

    _urlPrefixBtn_:null,

    _form_:null,

    init :function (boxDiv,form ) {
        let _this;
        this._boxDiv_ = boxDiv;
        this._form_ = form;
        this._lockBtn_ = this._boxDiv_.querySelector("button.btn.lock");

        this._urlPrefixBtn_ = this._boxDiv_.querySelector("button.btn.url-prefix");

        _this = this;
        this._lockBtn_.addEventListener("click",function () {
            _this.lockBtnClick();
        });
        /*this._form_.directoryField.addEventListener("input",function () {
            let input;
            input = _this._form_.directoryField;
            _this._form_.directory.value = input.value;
        });*/
        this._boxDiv_.querySelector("button.btn.url-List")
            .addEventListener("click",function () {
            // 显示 url 列表事件
                _this.urlList();
        });
        this._urlPrefixBtn_.addEventListener("click",function () {
            _this.urlPrefixBtnClick(this);
        });

    },lockBtnClick:function () {
        let input;
        input = this._form_.directoryField;
        if(input.hasAttribute("readonly")){
            // 取消锁定
            input.removeAttribute("readonly");
            this._lockBtn_.innerHTML = this._lockBtn_.getAttribute("data-on");
            this._form_.directory.value = "";
        }else {
            // 锁定
            input.setAttribute("readonly","readonly");
            this._lockBtn_.innerHTML = this._lockBtn_.getAttribute("data-off");
            this._form_.directory.value = input.value;
        }

    },
    /**
     * 显示 存储后的 url 列表 (文件名:url)
     */
    urlList:function () {
        StorageDetailBox.show("url列表",DropZoneStorage.forEachUrl());
    },urlPrefixBtnClick:function (btn) {
        let index ,root,key,span;
        index = btn.getAttribute("data-root-index");
        if(!index ){
            index = 0;
        }else {
            index = parseInt(index);
        }

        index = ++index % 3;
        btn.setAttribute("data-root-index",index);
        key = "data-root" + index;

        span = btn.querySelector("span.root");

        // 上传的根目录
        root = span.getAttribute(key);
        span.innerHTML = root;

        switch (root){
            case 'pub':btn.title = "公开目录";break;
            case 'pro':btn.title = "受保护目录";break;
            case 'pri':btn.title = "严格受保护目录";break;
            default:btn.title = null;
        }
        // 修改表单的存储级别ß
        this._form_.storageLevel.value = root;
    }
};

const StorageDetailBox = {

    _box_: null,

    _boxDialog_: null,

    init: function () {
        this._box_ = document.querySelector("div#detailModal");
        this._boxDialog_ = $(this._box_);
        this._boxDialog_.modal({"show": false});
    }, show: function (title, body) {

        this._box_.querySelector(".modal-title").innerHTML = "文件: " + title;
        this._box_.querySelector(".modal-body").innerHTML = body;
        this._boxDialog_.modal("show");
    }

};
